package at.fhj.itm;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;

public class CameraView extends Activity implements SurfaceHolder.Callback {

        private Camera _camera;
        private SurfaceView _surfaceView;
        private SurfaceHolder _surfaceHolder;
        private boolean _cameraInUse = false;
        private Camera.PictureCallback _jpgCallback;
        private Camera.PictureCallback _rawCallback;
        private ShutterCallback _shutterCallback;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);

                // setting up preview window
                getWindow().setFormat(PixelFormat.TRANSLUCENT);
                requestWindowFeature(Window.FEATURE_NO_TITLE);
                getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);
                setContentView(R.layout.camera);

                // getting view
                _surfaceView = (SurfaceView) findViewById(R.id.cameraSurface);
                _surfaceHolder = _surfaceView.getHolder();
                // add the surface callback
                _surfaceHolder.addCallback(this);
                _surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

                addCameraCallbacks();
        }

        private void addCameraCallbacks() {
                // picture callback - jpg image
                _jpgCallback = new Camera.PictureCallback() {

                        @Override
                        public void onPictureTaken(byte[] data, Camera camera) {
                                //TODO Redirect to DECODE!!!!
                                FileOutputStream outStream = null;
                                try {
                                        // write to local sandbox file system
                                        // outStream =
                                        // CameraDemo.this.openFileOutput(String.format("%d.jpg",
                                        // System.currentTimeMillis()), 0);
                                        // Or write to sdcard
                                        outStream = new FileOutputStream(String.format(
                                                        "/sdcard/IMG_tmp.png"));
                                        
                                        outStream.write(data);
                                        outStream.close();
                                        
                                        Log.i("Decode-Camera","Decoding taken Picture");
                                        
                                        String filePath = Environment.getExternalStorageDirectory().toString()+"/IMG_tmp.png";
                                        QRDecoder qrd = new QRDecoder();
                                        qrd.execute(filePath);
                                        
                                        Log.d("Camera-INFO:", "onPictureTaken - wrote bytes: " + data.length);
                                        
                                        startActivity(new Intent(getApplicationContext(), QRCodeDecode.class));
                                        
                                } catch (FileNotFoundException e) {
                                        e.printStackTrace();
                                } catch (IOException e) {
                                        e.printStackTrace();
                                } finally {
                                }
                                Log.d("Camera-INFO:", "onPictureTaken - jpeg");
                        }
                };

                // picture callback - raw image
                _rawCallback = new Camera.PictureCallback() {

                        @Override
                        public void onPictureTaken(byte[] data, Camera camera) {
                                // handle raw image data (may be null if hardware memory is
                                // insufficient)

                        }
                };

                // shutter callback
                _shutterCallback = new ShutterCallback() {

                        @Override
                        public void onShutter() {
                                // here we could add a sound effect to indicate picture is being
                                // taken
                        }

                };

                // add a clicklistener to surface to make camera take a picture
                _surfaceView.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                                // take picture - if you don't need raw, just pass in null
                                _camera.takePicture(_shutterCallback, _rawCallback,
                                                _jpgCallback);
                        }

                });
        }

        @Override
        // called when changes happen to the surface
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                        int height) {
                try {
                        // check to see if camera is already in preview mode
                        if (_cameraInUse) {
                                _camera.stopPreview();
                        }

                        // set size of camera
                        Camera.Parameters p = _camera.getParameters();
                        p.setPreviewSize(width, height);
                        _camera.setParameters(p);
                        _camera.setPreviewDisplay(holder);

                        // start preview
                        _camera.startPreview();
                        _cameraInUse = true;
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }

        @Override
        // called the first time surface is created
        public void surfaceCreated(SurfaceHolder holder) {
                // make camera ready for use
                _camera = Camera.open();
        }

        @Override
        // called when surface is destroyed
        public void surfaceDestroyed(SurfaceHolder holder) {
                // stop preview and release camera
                _camera.stopPreview();
                _cameraInUse = false;
                _camera.release();
        }

}
